<template>
  <div class="content">
    <el-row class="bgW">
      <el-col :span="22">
        <!--检索条件-->
        <el-form class="search" :inline="true" label-suffix="：" size="mini" :model="search">

          <el-form-item label="日期">
            <el-date-picker v-model="search.time" type="date" class="w200" placeholder="选择日期"
              value-format="yyyy-MM-dd"></el-date-picker>
          </el-form-item>

          <el-form-item label="门店/门诊" v-if="!userInfo.shop_id">
            <el-select v-model="search.shop_id" clearable remote filterable :remote-method="remoteMethod"
              placeholder="请输入" class="w120">
              <el-option v-for="item in options.shop_id" :key="item.shopId" :label="item.shopName"
                :value="item.shopId" />
            </el-select>
          </el-form-item>

          <el-form-item label="提示">
            <i class="el-icon-warning" style="color: #EF9187;background-color: #EF9187;"></i>已核销&nbsp;
            <i class="el-icon-warning" style="color: #F7D47F;background-color: #F7D47F;"></i>未核销&nbsp;
            <i class="el-icon-warning" style="color: #FFFFFF;background-color: #FFFFFF;border: solid 1px black;"></i>未预约
          </el-form-item>

        </el-form>
      </el-col>
      <el-col :span="2" style="text-align: right;">
        <el-button type="primary" icon="el-icon-search" size="mini" @click="getList('search')">搜索</el-button>
      </el-col>
    </el-row>
    <div class="accountCon">
      <div class="btnBox">
        <!-- <el-button
          v-if="!userInfo.shop_id"
          type="primary"
          :disabled="!idList.length"
          class="mb10"
          size="mini"
          @click="hint('导出选中列表')"
        >导出数据</el-button> -->
      </div>
      <!--列表-->
      <el-row>
        <el-col :span="24">
          <el-table 
            :data="list" 
            size="small" 
            border 
            :cell-style="cellStyle" 
            :header-cell-style="$style.rowClass"
          >
            <ElTableColumn label="员工" prop="person_name" />
            <el-table-column v-for="(item,index) in times" :label="item" align="center">
              <template slot-scope="scope">
                <!-- 使用v-for循环显示同一时间段的所有客户 -->
                <div 
                  v-for="(customer, customerIndex) in getCustomersForTimeSlot(scope.row.distribution[index])" 
                  :key="customer.id || customerIndex"
                  class="hand customer-item"
                  :class="{
                    'status-unverified': customer.status === 0,
                    'status-verified': customer.status === 1
                  }"
                  @click="tapBtn(scope.row.shop_person_id, customer, scope.row.person_name)"
                >
                  {{customer.name || customer.customer}} &nbsp;
                  <!-- 显示客户序号，帮助用户区分同一时间段的不同客户 -->
                  <span v-if="hasMultipleCustomers(scope.row.distribution[index])" class="customer-index">
                    ({{customerIndex + 1}})
                  </span>
                </div>
                <!-- 如果该时间段可预约更多客户，显示添加按钮 -->
                <div 
                  v-if="canAddMoreCustomers(scope.row.distribution[index])"   
                  class="hand add-customer"
                  @click="addCustomer(scope.row.shop_person_id, scope.row.distribution[index], scope.row.person_name)"
                >
                  <i class="el-icon-plus"></i> 
                  <!-- 添加 -->
                </div>
              </template>
            </el-table-column>
          </el-table>
          <el-dialog :title="info.person_name" :visible.sync="dialogVisible" width="30%">
            <el-form  label-suffix="：" :inline="true" size="mini" :model="info">
              <el-form-item label="客户">
                <el-select v-model="info.customer_id" clearable remote filterable placeholder="请输入" class="w120">
                  <el-option v-for="item in customerlist" :key="item.id" :label="item.customer_name" :value="item.id" />
                </el-select>
              </el-form-item>
              <el-form-item label="时间">
                  <el-time-select placeholder="起始时间" v-model="info.start_time" :picker-options="{
                    start: '09:00',
                    step: '00:30',
                    end: '20:00'
                  }"
                  v-if="!userInfo.shop_id"
                  >
                </el-time-select>
                <el-time-select placeholder="结束时间" v-model="info.end_time" :picker-options="{
                    start: '09:00',
                    step: '00:30',
                    end: '20:00',
                    minTime: info.start_time
                  }"
                  v-if="!userInfo.shop_id"
                  >
                </el-time-select>
                <el-time-select placeholder="起始时间" v-model="info.start_time" :picker-options="{
                    start: shopInfo. start_time,
                    step: shopInfo.time_default == 1 ? '00:30' :'01:00',
                    end: shopInfo.end_time
                  }"
                  v-if="userInfo.shop_id"
                  >
                </el-time-select>
                <el-time-select placeholder="结束时间" v-model="info.end_time" :picker-options="{
                    start: shopInfo.start_time,
                    step: shopInfo.time_default == 1 ? '00:30' :'01:00',
                    end: shopInfo.end_time,
                    minTime: info.start_time
                  }"
                  v-if="userInfo.shop_id"
                  >
                </el-time-select>
              </el-form-item>

            </el-form>
            <span slot="footer" class="dialog-footer">
              <el-button @click="dialogVisible = false">取 消</el-button>
              <el-button type="primary" @click="add()">确 定</el-button>
            </span>
          </el-dialog>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import { newbooksList,personcustomerList,submitBooks,getBookId,cancelBook,getShopInfo } from "@/api/client";
import { getShopList } from "@/api/shop";

class Search {
  time=""; //预约时间
  shop_id="73782774834649"; // 归属门店
}
class Info{
  person_name="";
  person_id=0;
  customer_id="";
  start_time="";
  end_time="";
  date = "";
}
class Options {
  shop_id = [
    {'shopId':73782774834649,'shopName':'大学路'}
  ];
}
class Book{
      bookId='';
      person='';
      platform=2;
      today='';
      yy_date='';
      yy_time='';
}
export default {
  name: "StaffList",
  data() {
    return {
      search: new Search(), // 检索条件
      options: new Options(),
      info:new Info(),
      book:new Book(),
      customerlist:[],
      shopInfo:{},
      list: [], // 数据展示
      times:[],
      dialogVisible:false,
      currentTimeSlot: null, // 当前操作的时间段
      currentCustomerIndex: -1, // 当前操作的客户索引
      isAddingNewCustomer: false // 是否正在添加新客户
    };
  },
  computed: {
    ...mapGetters(["userInfo"])
  },
  mounted() {
    if (this.userInfo.shop_id) {
      this.search.shop_id = this.userInfo.shop_id;
    } 
    else {
      this.remoteMethod('73782774834649') 
      this.search.shop_id = '73782774834649';
      
    }
    this.getList();
    this.getShopInfo();
  },
  methods: {
    getShopInfo(){
      getShopInfo({
        shop_id: this.userInfo.shop_id
      }).then(res => {
        this.shopInfo= res.data
      })  
    },
   getCurrentDate() {
      const now = new Date();
      return {
        year: now.getFullYear(),
        month: now.getMonth() + 1, // 注意：月份从 0 开始，所以要加 1
        day: now.getDate(),
        formatted: `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')}`
      };
    },
    // 获取列表
    getList(option) {
        newbooksList({
            ...this.search,
        }).then(res => {
            this.list = res.data.data;
            this.times = res.data.times;
        });
    },
    
    // 获取时间段的所有客户
    getCustomersForTimeSlot(timeSlot) {
      // 如果customer是字符串，转为包含单个客户的数组
      if (typeof timeSlot.customer === 'string') {
        return [{
          name: timeSlot.customer,
          status: timeSlot.status,
          id: timeSlot.id || null,
          time: timeSlot.time
        }];
      }
      
      // 如果customer是数组，直接返回
      if (Array.isArray(timeSlot.customer)) {
        return timeSlot.customer.map(customer => ({
          ...customer,
          time: timeSlot.time
        }));
      }
      
      // 其他情况返回空数组
      return [];
    },
    
    // 检查时间段是否有多个客户
    hasMultipleCustomers(timeSlot) {
      return this.getCustomersForTimeSlot(timeSlot).length > 1;
    },
    
    // 检查是否可以添加更多客户
    canAddMoreCustomers(timeSlot) {
      // 只要时间段有客户列表，且客户数量小于2，就可以添加
      return this.getCustomersForTimeSlot(timeSlot).length < 2;
    },
    
    // 添加新客户
    addCustomer(person_id, timeSlot, person_name) {
      this.isAddingNewCustomer = true;
      this.currentTimeSlot = timeSlot;
      this.currentCustomerIndex = -1; // -1表示添加新客户
      
      this.info = new Info();
      this.info.person_id = person_id;
      this.info.person_name = person_name;
      this.info.date = this.search.time;
      this.info.start_time = timeSlot.time;
      
      this.customerlist = [];
      personcustomerList({
        person_id: person_id
      }).then(res => {
        this.customerlist = res.data;
        this.dialogVisible = true;
      });
    },
    
    // 处理单元格点击事件
    tapBtn(person_id, customer, person_name) {
      this.isAddingNewCustomer = false;
      this.currentTimeSlot = customer;
      
      this.info = new Info();
      this.info.person_id = person_id;
      this.info.person_name = person_name;
      this.info.date = this.search.time;
      this.info.start_time = customer.time;
      this.customerlist = [];
         
      if (customer.status === 0) { // 未核销
        getBookId({
          ...this.info,
          customer_id: customer.id
        }).then(res => {
          this.book = res.data.data;
        });
          console.log(this.book,"res11")
        
        let str = "此操作将取消【" + (customer.name || customer.customer) + "】预约护理师【" + person_name + "】的预约记录";
        this.$confirm(str, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          cancelBook({
            bookId:  this.book.id,
            person:this.book.customer_id,
            platform:2,
            today:this.search.time.replace(/-/g, '') || this.getCurrentDate().formatted.replace(/-/g, ''),
            yy_date:this.book.yy_year+'-'+this.book.yy_date,
            yy_time: this.book.yy_time_str.split(',')
          }).then(res => {
            if(res.data.error == '取消成功'){
                this.$message({
                  type: 'success',
                  message: '取消预约成功!'
                });
                this.getList();
            }else{
              this.$message({
                  type: 'error',
                  message: res.data.error
                });
              }
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消操作'
          });
        });
      }
      
      if (customer.status === 1) { // 已核销
        this.$message({
          type: 'warning',
          message: '已核销'
        });
      }
      
      if (customer.status === 2) { // 未预约
        this.dialogVisible = true;
        personcustomerList({
          person_id: person_id
        }).then(res => {
          this.customerlist = res.data;
          this.getList();
        });
      }
    },
generateTimePoints(startTime, endTime, intervalMinutes = 30) {
  const [startHours, startMinutes] = startTime.split(':').map(Number);
  const [endHours, endMinutes] = endTime.split(':').map(Number);

  const startTotalMinutes = startHours * 60 + startMinutes;
  const endTotalMinutes = endHours * 60 + endMinutes;
  const timePoints = [];

  // 计算第一个有效时间点（向上取整到最近的间隔）
  const firstValidMinutes = Math.ceil(startTotalMinutes / intervalMinutes) * intervalMinutes;

  // 生成时间点数组
  for (let minutes = firstValidMinutes; minutes <= endTotalMinutes; minutes += intervalMinutes) {
    const hours = Math.floor(minutes / 60);
    const mins = minutes % 60;
    timePoints.push(`${hours.toString().padStart(2, '0')}:${mins.toString().padStart(2, '0')}`);
  }

  return timePoints;
},
    // 确认添加预约
    add() {
      this.dialogVisible = false;
      this.info.shop_id=this.userInfo.shop_id;
      this.info.shop_person_id=this.info.person_id;

      if(this.shopInfo.time_default == 1){
        this.info.yy_time=this.generateTimePoints(this.info.start_time,this.info.end_time,30);
      }else{
        this.info.yy_time=this.generateTimePoints(this.info.start_time,this.info.end_time,60);

      }
            //  today:this.search.time.replace(/-/g, '') || this.getCurrentDate().formatted.replace(/-/g, ''),
      // 准备提交数据
      const [year, month, day] = this.search.time.split('-');
      const submitData = {
        customer_id:this.info.customer_id,
        shop_person_id: this.info.person_id,
        yy_year: year ||  this.getCurrentDate().year,
        yy_date: month ?  month +'-'+ day : this.getCurrentDate().month+ '-'+this.getCurrentDate().day,
        yy_time: this.info.yy_time,
        shop_id: this.userInfo.shop_id,
        status: 0 // 默认为未核销状态
      };
      
 
      
      // 提交预约
      submitBooks(submitData).then(res => {
        if(res.data.error == '预约成功'){
            this.$message({
              type: 'success',
              message: '预约成功!'
            });
            this.getList();
        }else{
          this.$message({
              type: 'error',
              message: res.data.error
            });
        }
      });
    },
    
    // 单元格样式
    cellStyle({row, column, rowIndex, columnIndex}){
      if(columnIndex <= 0){
        return 'background:#E7FEB5;text-align:center'
      }
      
      // 获取时间段的客户列表
      const customers = this.getCustomersForTimeSlot(row.distribution[columnIndex-1]);
      
      // 如果没有客户，使用默认背景色
      if (customers.length === 0) {
        return 'text-align:center'
      }
      
      // 如果有客户，根据第一个客户的状态设置背景色
      const status = customers[0].status;
      
      // 根据状态设置背景色
      if(status === 1) { // 已核销
        return 'background:#EF9187;text-align:center'
      }
      if(status === 0) { // 未核销
        return 'background:#F7D47F;text-align:center'
      }

      return 'text-align:center';
    },

    // 搜索门店
    remoteMethod(e) {
      getShopList({ page: 1, limit: 100000, shopName: e }).then(res => {
        this.options.shop_id = res.list;
      });
    },
  }
};
</script>

<style lang="scss" scoped>
.mainColor {
  color: #2dc0a3;
}
::v-deep .el-table .cell{
  padding: 8px 0  0 0!important;
}
::v-deep .el-table .el-table__cell{
  padding: 8px 0 0 0!important;
}
::v-deep .el-table--small .el-table__cell{
  padding: 8px 0 0 0 !important;
}
.content {
  height: calc(100% - 56px);
  overflow-y: auto;
}
.bgW {
  background: #fff;
  border-radius: 3px;
  padding: 10px;
  margin-bottom: 20px;
}

.el-form-item {
  margin: 5px 40px 3px 0;
}
.accountCon {
  background: #fff;
  padding: 0px 10px 80px;
  .btnBox {
    display: flex;
    justify-content: space-between;
  }
}

// 客户列表样式
.customer-item {
  padding: 2px 0;
  cursor: pointer;
  font-size:13px;
  
  // 客户序号样式
  .customer-index {
    font-size: 10px;
    color: #666;
    margin-left: 4px;
  }
  
  // 根据客户状态设置不同颜色
  &.status-unverified {
    color: #333;
    background: rgb(247, 212, 127);
    padding: 8px;
  }
  
  &.status-verified {
    color: #333;
    background: rgb(239, 145, 135);
    padding: 8px;
    // text-decoration: line-through;
  }
}

// 添加客户按钮样式
.add-customer {
  padding: 2px 0;
  color: #409EFF;
  cursor: pointer;
  
  i {
    margin-right: 4px;
  }
}
</style>
